// 函数组件
import React, { useState, useEffect, useContext, } from 'react';
import { Input, Form, Tabs, Button, Cascader, Select, Checkbox, Table, Switch, Modal, message, ConfigProvider, Radio } from 'antd';
import "./css/AddShop.less"
import type { ColumnsType } from 'antd/es/table';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ExclamationCircleFilled } from '@ant-design/icons';
import zh_CN from 'antd/es/locale/zh_CN';
import ZoneDialog from './child/ZoneDialog';
import { useNavigate, useLocation } from "react-router-dom";
import type { TabsProps } from 'antd';
import type { CheckboxValueType, CheckboxOptionType } from 'antd/es/checkbox/Group';
import { addZone, addZoneShop, getBrand, getClassify, getLabel, selectGoods } from '../../../api/operationApi';
import Item from 'antd/es/list/Item';
import { use } from 'echarts';
import type { RadioChangeEvent } from 'antd';


interface DataType {
    goodsId: number,
    goodsImg: string,
    goodsName: string,
    goodsSerNum: number,
    goodsPriceRange: number,
    categoryName: string,
    brandName: string,
    goodsSell: number,
}


// 联级选择
interface Option {
    value: string;
    label: string;
    children?: Option[];
}

// 表单布局
const layout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 20,
    },
};


function AddShop() {
    const navigate = useNavigate();

    // 表格列
    const columns: ColumnsType<DataType> = [
        {
            title: '序号',
            dataIndex: 'goodsId',
            align: 'center',
            width: '15%'
        },
        {
            title: '商品图片',
            dataIndex: 'goodsImg',
            align: 'center',
            render: (value, record, index) => {
                return (
                    <img src={value} width={50} height={50} />
                )
            }
        },

        {
            title: '商品名称',
            dataIndex: 'goodsName',
            align: 'center',
        },
        {
            title: '货号',
            dataIndex: 'goodsSerNum',
            align: 'center',
        },
        {
            title: '价格',
            dataIndex: 'goodsPriceRange',
            align: 'center',
        },

        {
            title: '分类',
            dataIndex: 'categoryName',
            align: 'center',
        },
        {
            title: '品牌',
            dataIndex: 'brandName',
            align: 'center',
        },
        {
            title: '销量',
            dataIndex: 'goodsSell',
            align: 'center',
        },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: '16%',
            render: (value, record) => (
                <div>
                    <button className='add' onClick={()=>clickAdd(record)}>添加</button>
                </div>
            ),
        },
    ];


    const [currentPage, setCurrentPage] = useState<number>(1) // 当前页
    const [pageSize, setPageSize] = useState<number>(10)  // 一页条数
    const [count, setCount] = useState<number>() // 总数

    const [keyWord, setKeyWord] = useState<string>()  // 关键字
    const [brand, setBrand] = useState<string>() // 品牌
    const [sortWay, setSortWay] = useState<string>() // 排序方式
    const [label, setLabel] = useState<string>()  // 标签
    const [type, setType] = useState<string>() // 分类


    // 表格数据
    const [data, setData] = useState<DataType[]>([])
    // 1、表格渲染数据
    useEffect(() => {
        getData(currentPage, pageSize, keyWord, brand, sortWay, label, type)
    }, [currentPage, pageSize])

    // 1-1 删除当前页最后一项，页码改变
    useEffect(() => {
        if (currentPage > 1 && data.length === 0) {
            setCurrentPage(currentPage - 1)
        }
    }, [data])

    // 1-2 获取数据
    // 接收传递的专区id
    const location = useLocation()
    async function getData(currentPage: number, pageSize: number, keyWord?: string, brand?: string, sortWay?: string, label?: string, type?: string) {
        console.log('专区id', location.state.tsaId);
        let res = await selectGoods(
            {
                "brand": brand, // 品牌
                "currentPage": currentPage,
                "keyWord": keyWord,
                "label": label, // 标签
                "pageSize": pageSize,
                "sortWay": sortWay,  // 排序
                "tsaId": location.state.tsaId,
                "type": type  // 分类
            }
        )
        // console.log('res', res);

        setCount(res.data.total)
        setData(res.data.vyyGoods)

    }

    // 1-3 改变页码
    const getPageContent = (currentPage: number, pageSize: number) => {
        setCurrentPage(currentPage)
        setPageSize(pageSize)
    }


    // 2、筛选查询部分
    const [form] = Form.useForm();

    // 页面商品分类数据
    const [option, setOption] = useState<Option[]>([])
    const [brandOption, setBrandOption] = useState<{}[]>() // 品牌下拉选择
    const [labelOption, setLabelOption] = useState<(string | number | CheckboxOptionType)[]>() // 标签下拉选择


    // 获取分类数据 和 品牌 标签
    useEffect(() => {
        getClassify().then(res => {
            // console.log('分类数据', res);

            let arr = res.data.map((item: any) => {
                function getChild(item2: any) {
                    // console.log('item2',item2);
                    if (item2.children.length == 0) {
                        return {
                            value: item2.name,
                            label: item2.name,
                        };
                    }
                    return {
                        value: item2.name,
                        label: item2.name,
                        children: item2.children.map((i: any) => {
                            if (i.children.length == 0) {
                                return {
                                    value: i.name,
                                    label: i.name,
                                };
                            }
                            // console.log('i', i);
                            return getChild(i)
                        })
                    }
                }
                return getChild(item)

            })
            // console.log('arr', arr);
            setOption(arr)

        })

        getBrand().then(res => {
            let newData = res.data.map((item: any) => {
                let obj: any = {}
                obj['value'] = item
                obj['label'] = item
                return item = obj
            })
            setBrandOption(newData)

        })

        getLabel().then(res => {
            // console.log('标签',res);
            let newData = res.data.map((item: any) => {
                let obj: any = {}
                obj['value'] = item.labelName
                obj['label'] = item.labelName
                return item = obj
            })

            // console.log('newData',newData);
            setLabelOption(newData)

        })

    }, [])


    // 标签改变
    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
    };


    // 点击重置
    const reset = () => {
        form.resetFields()
        setKeyWord('')
        setBrand('')
        setSortWay('')
        setLabel('')
        setType('')
        getData(currentPage, pageSize)

        message.success('重置成功')
    }

    // 点击筛选
    const filter = (values: any) => {
        let type: string = ''
        if (values.type) {
            type = values.type[values.type.length - 1]
            console.log('type', type);
        }

        setKeyWord(values.key)
        setBrand(values.brandName)
        setSortWay(values.sort)
        setLabel(values.tag)
        setType(type)


        getData(currentPage, pageSize, values.key, values.brandName, values.sort, values.tag, type)

        message.success('筛选成功')
    }


    // 3、数据列表排序下拉选项
    const selectOption: {}[] = [
        { value: '按销量顺序', label: '按销量顺序' },
        { value: '按销量倒序', label: '按销量倒序' }
    ]

    const changeSort = async (e: string) => {
        setSortWay(e)
        getData(currentPage, pageSize, keyWord, brand, e, label, type)
        message.success('排序成功')
    }

    // 4、添加商品
    const { confirm } = Modal;
    const clickAdd = (item:DataType)=>{
        console.log('item',item);
        confirm({
            title: '确定将该商品添加至专区吗?',
            icon: <ExclamationCircleFilled />,
            content: '冲冲冲~',
            async onOk() {
                await addZoneShop({
                    tsaId: location.state.tsaId,
                    goodsId:item.goodsId 
                })
                getData(currentPage, pageSize, keyWord, brand, sortWay, label, type)
                // console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'data', data);
                message.success('添加成功')
            },
            onCancel() {
                message.warning('取消操作')
            },
        });
    }



    return (
        <div className='AddShop'>
            {/* 头部 */}
            <div className='page-top'>
                {/*左边标题  */}
                <div className='page-title'>
                    <p>专区管理</p>
                </div>
            </div>

            {/* 内容区 */}
            <div className='page-context'>
                {/* 查询部分 */}
                <div className='banner-search'>
                    <p className='search-title'>筛选查询</p>

                    <div className='search-input'>
                        <Form
                            {...layout}
                            name="addshop-form"
                            onFinish={filter}
                            form={form}
                            size={'middle'}
                        >

                            <Form.Item name='key' label="关键字" className='operate-select-item' >
                                <Input placeholder='标题关键字' />
                            </Form.Item>

                            <Form.Item label='分类' className='operate-select-item' name='type'>
                                <Cascader placeholder="请选择类型" options={option} changeOnSelect />
                            </Form.Item>

                            <Form.Item label='品牌' className='operate-select-item' name='brandName'>
                                <Select
                                    style={{ width: 120 }}
                                    allowClear
                                    options={brandOption}
                                    placeholder='请选择品牌'
                                />
                            </Form.Item>

                            <Form.Item name='sort' label="商品排序" className='operate-sort-item' >
                                <Select
                                    placeholder="全部"
                                    style={{ width: 120 }}
                                    allowClear
                                    options={[{ value: '按销量顺序', label: '按销量顺序' }, { value: '按销量倒序', label: '按销量倒序' }]}
                                />
                            </Form.Item>

                            <Form.Item
                                labelCol={{ span: 1.2 }}
                                labelAlign='left'
                                name='tag'
                                label="标签筛选"
                                className='operate-tag-item'>
                                <Radio.Group options={labelOption} onChange={onChange} />
                            </Form.Item>


                            <Form.Item
                                wrapperCol={{
                                    ...layout.wrapperCol,
                                    offset: 8,
                                }}
                                className='search-btn'
                            >
                                <div className='btn'>
                                    <Button onClick={reset} className='reset'>重置</Button>
                                    <Button htmlType="submit" className='filter'>筛选</Button>
                                </div>

                            </Form.Item>
                        </Form>
                    </div>

                </div>

                {/* 数据表格部分 */}
                <div className='data-list'>
                    <div className='list-title'>
                        <p>商品列表</p>
                        <div className='list-operation'>
                            <div className='operation-one'>
                                <p>排序方式</p>
                                <Select
                                    className='select-shelf'
                                    placeholder="排序方式"
                                    style={{ width: 140 }}
                                    allowClear
                                    options={selectOption}
                                    onChange={changeSort}
                                />
                            </div>
                            {/* <div>
                                <button className='add'>批量添加</button>
                            </div> */}
                        </div>
                    </div>

                    {/* 表格部分 */}
                    <ConfigProvider locale={zh_CN}>
                        <Table
                            columns={columns}
                            dataSource={data}
                            scroll={{ y: 270 }}
                            rowKey={item => item.goodsId}
                            pagination={{
                                position: ['bottomCenter'],
                                total: count,
                                pageSize: pageSize,
                                onChange: getPageContent,
                                defaultPageSize: 3,
                                pageSizeOptions: [3, 5, 10, 15],
                                showQuickJumper: true,
                                showSizeChanger: true,
                            }}
                        />
                    </ConfigProvider>


                </div>
            </div>


        </div>
    )
}

export default AddShop